{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Anaconda 默认不包含 docx工具包，需要执行以下脚本进行安装\n",
    "# 如果本地没有安装工具包，请去掉“#”，再执行\n",
    "# !pip install -i https://mirrors.aliyun.com/pypi/simple/ python-docx"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1、导入包并创建一个 Word 文档对象"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import docx\n",
    "# 从docx 工具包中导入要使用的对象\n",
    "from docx import Document\n",
    "# 字号、尺寸、大小单位：pt(点数或磅)、px(像素)、inch(英寸)、cm(厘米)等等\n",
    "from docx.shared import Pt, Inches \n",
    "# 文本相关段落对齐\n",
    "from docx.enum.text import WD_PARAGRAPH_ALIGNMENT\n",
    "# RGB 颜色，用于字体颜色（网上搜索“在线调色板”）\n",
    "from docx.shared import RGBColor \n",
    "# 标准预设颜色。用于字体突出显示背景色 （默认为 AUTO 自动上色，通常为黑色）\n",
    "from docx.enum.text import WD_COLOR_INDEX\n",
    "\n",
    "# Document 不包含文件路径就是在内存中创建 Word 对象\n",
    "document = Document()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table width=\"100%\" border=\"0\">\n",
    "<tr>\n",
    "  <td valign=\"top\" width=\"45%\"  style=\"vertical-align:top; text-align:left;background-color:#ddffdd;\">\n",
    " \n",
    " **<font color=\"blue\" size=\"3px\"> RGB 在线调色板截图</font>**\n",
    "    <img src=\"images/RGB调色板.png\" align=\"center\"/>\n",
    "  </td>\n",
    "  <td style=\"vertical-align:top; text-align:left;background-color:#ddffdd\">\n",
    "\n",
    "**<font color=\"blue\" size=\"3px\"> WD_COLOR_INDEX 颜色值</font>**\n",
    " \n",
    "<img src=\"images/WD_COLOR_INDEX.png\" align=\"center\"/>\n",
    "\n",
    "  </td>\n",
    " </tr>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 2、全局样式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def set_global_style(doc):\n",
    "    # 以下仅作为参考，大家可以自定义全局样式（不设置就是默认）\n",
    "    # 设置全局字体（英文字体）\n",
    "    doc.styles[\"Normal\"].font.name=\"宋体\"\n",
    "    # 设置全局字体（中文字体）\n",
    "    doc.styles[\"Normal\"]._element.rPr.rFonts.set(docx.oxml.ns.qn('w:eastAsia'), '宋体')\n",
    "    # 设置正文全局颜色为灰色（网上搜索“在线调色板”）\n",
    "    doc.styles[\"Normal\"].font.color.rgb=RGBColor(20,20,20)\n",
    "    # 设置正文全局大小为 10\n",
    "    doc.styles[\"Normal\"].font.size=Pt(10)\n",
    "    # 设置全局2级标题的字体大小为 20\n",
    "    doc.styles[\"Heading 2\"].font.size=Pt(20)\n",
    "\n",
    "set_global_style(document)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3、文本块样式操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建一个空字符串段落 p1\n",
    "p1 = document.add_paragraph('')\n",
    "# 在段落 p1 后增加文字块 \n",
    "p1.add_run('该段落有：')\n",
    "p1.add_run('粗体字 ').bold = True # bold 设置为真（布尔类型）\n",
    "p1.add_run('斜体字 ').italic = True # italic 设置为真（布尔类型）\n",
    "p1.add_run('下划线 ').underline = True # underline 设置为真（布尔类型）\n",
    "# 增加有颜色的文字块（网上搜索“在线调色板”）\n",
    "p1.add_run('蓝色字 ').font.color.rgb = RGBColor(0, 0, 255)\n",
    "\n",
    "# 增加 字号=20、8磅 的文字块\n",
    "p1.add_run('20号字 ').font.size = Pt(20)\n",
    "p1.add_run('8号字 ').font.size = Pt(8)\n",
    "\n",
    "# 如果要修改 run对象的多个样式属性，赋值给一个变量，如：r_color\n",
    "r_color = p1.add_run('黄底红字 ')\n",
    "r_color.font.color.rgb = RGBColor(255, 0, 0) # 修改文字的颜色\n",
    "\"\"\"\n",
    "BLACK(1),BLUE(2),TURQUOISE(3),BRIGHT_GREEN(4),PINK(5),RED(6),YELLOW(7),WHITE(8)\n",
    "DARK_BLUE(9),TEAL(10)GREEN(11),VIOLET(12),DARK_RED(13),DARK_YELLOW(14),GRAY_50(15),GRAY_25(16)\n",
    "\"\"\"\n",
    "r_color.font.highlight_color=WD_COLOR_INDEX.YELLOW # 修改突显背景色\n",
    "\n",
    "# 增加指定字体的文字块\n",
    "r_fnt = p1.add_run('微软雅黑字  ')\n",
    "r_fnt.font.name = '微软雅黑' # 英文字体改为微软雅黑\n",
    "# 中文字体改为微软雅黑\n",
    "r_fnt._element.rPr.rFonts.set(docx.oxml.ns.qn('w:eastAsia'), '微软雅黑')\n",
    "\n",
    "save_file = r'.\\files\\Word_样式布局.docx'\n",
    "# 保存内存中的document对象到文件\n",
    "document.save(save_file)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 4、使用WORD默认字符样式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "p2 = document.add_paragraph('字符样式演示：')\n",
    "# style参考课程结尾提供的“WORD 默认模板中的样式：字符样式”\n",
    "p2.add_run('Book Title ',style=\"Book Title\")\n",
    "p2.add_run('Macro Text Char ',style=\"Macro Text Char\")\n",
    "p2.add_run('Emphasis ',style=\"Emphasis\")\n",
    "p2.add_run('Quote Char ',style=\"Quote Char\")\n",
    "\n",
    "# 保存内存中的document对象到文件\n",
    "document.save(save_file)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 5、使用WORD默认段落样式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 添加一级标题\n",
    "document.add_heading('有序列表', level=1)\n",
    "# 添加 3 个有序列表样式段落（List Number）\n",
    "# style 参考课程结尾提供的“WORD 默认模板中的样式：段落样式”\n",
    "p_no1 = document.add_paragraph(\n",
    "    'Document 对象表示整个文档', style='List Number'\n",
    ")\n",
    "# 样式：字号=10磅 \n",
    "p_no1.runs[0].font.size = Pt(10)\n",
    "\n",
    "p_no2 = document.add_paragraph(\n",
    "    'Paragraph 对象表示段落（每一次回车会产生新段落）', \n",
    "    style='List Number'\n",
    ")\n",
    "\n",
    "p_no3 = document.add_paragraph(\n",
    "    'Run 对象表示相同样式的文本延续', style='List Number'\n",
    ")\n",
    "# 英文字体改为微软雅黑\n",
    "p_no3.runs[0].font.name = '微软雅黑'\n",
    "# 中文字体改为微软雅黑\n",
    "p_no3.runs[0]._element.rPr.rFonts.set(docx.oxml.ns.qn('w:eastAsia'), '微软雅黑')\n",
    "\n",
    "# 保存内存中的document对象到文件\n",
    "document.save(save_file)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 6、段落、图片的对齐"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "document.add_heading('Word对象结构图居中显示', level=1)\n",
    "# 添加图片并且居中\n",
    "paragraph = document.add_paragraph()\n",
    "\"\"\"\n",
    "WD_PARAGRAPH_ALIGNMENT.LEFT：段落左对齐\n",
    "WD_PARAGRAPH_ALIGNMENT.CENTER：段落居中对齐\n",
    "WD_PARAGRAPH_ALIGNMENT.RIGHT：段落右对齐\n",
    "WD_PARAGRAPH_ALIGNMENT.JUSTIFY：段落两端对齐\n",
    "\"\"\"\n",
    "# 图片居中设置\n",
    "paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n",
    "\n",
    "run = paragraph.add_run(\"\")\n",
    "run.add_picture(r'.\\images\\Word对象结构图.png',width=Inches(4))\n",
    "\n",
    "# 保存内存中的document对象到文件\n",
    "document.save(save_file)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 思考题"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1、以下代码如果经常使用就比较麻烦，字体要设置两次，怎么解决？\n",
    "\n",
    "```python\n",
    "\n",
    "r = p1.add_run('微软雅黑字体  ')\n",
    "r.font.name = '微软雅黑' # 这里只能将英文字体改为 微软雅黑\n",
    "\n",
    "# 这里将输入语句中的中文部分字体变为微软雅黑\n",
    "r._element.rPr.rFonts.set(docx.oxml.ns.qn('w:eastAsia'), '微软雅黑')\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 思考题 1 的解决办法\n",
    "def set_font_name(run , font_name):\n",
    "    \"\"\"\n",
    "    修改文字块的中、英文字体\n",
    "    :param run: 文字块\n",
    "    :param font_name: 字体\n",
    "    :return: \n",
    "    \"\"\"\n",
    "    r.font.name = font_name\n",
    "    r._element.rPr.rFonts.set(docx.oxml.ns.qn('w:eastAsia'), font_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 思考题 1 ：将代码复制过来，尝试使用 set_font_name\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2、通过循环把下面所有“字符样式”保存到一个Word文档\n",
    "\n",
    "* 提示：\n",
    "\n",
    "```\n",
    "p2 = document.add_paragraph('字符样式演示：')\n",
    "for style in char_styles:\n",
    "  p2.add_run(style,style=style)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# WORD 默认模板中的样式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table width=\"100%\" border=\"0\">\n",
    "<tr>\n",
    "  <td valign=\"top\" width=\"50%\" style=\"vertical-align:top; text-align:left;background-color:#ddffdd\">\n",
    "                                                                                           <font color=\"blue\" size=\"3px\"> 段落样式</font>                                                                                      \n",
    "\n",
    "* Normal\n",
    "* Body Text\n",
    "* Body Text 2\n",
    "* Body Text 3\n",
    "* Caption\n",
    "* Heading 1\n",
    "* Heading 2\n",
    "* Heading 3\n",
    "* Heading 4\n",
    "* Heading 5\n",
    "* Heading 6\n",
    "* Heading 7\n",
    "* Heading 8\n",
    "* Heading 9\n",
    "* Intense Quote\n",
    "* List\n",
    "* List 2\n",
    "* List 3\n",
    "* List Bullet\n",
    "* List Bullet 2\n",
    "* List Bullet 3\n",
    "* List Continue\n",
    "* List Continue 2\n",
    "* List Continue 3\n",
    "* List Number\n",
    "* List Number 2\n",
    "* List Number 3\n",
    "* List Paragraph\n",
    "* Macro Text\n",
    "* No Spacing\n",
    "* Quote\n",
    "* Subtitle\n",
    "* TOCHeading\n",
    "* Title\n",
    "  </td>\n",
    "  <td valign=\"top\" width=\"50%\" style=\"vertical-align:top; text-align:left;background-color:#ddffdd\">\n",
    "      \n",
    "   <font color=\"blue\" size=\"3px\"> 字符样式</font>\n",
    "\n",
    "\n",
    "* Body Text Char\n",
    "* Body Text 2 Char\n",
    "* Body Text 3 Char\n",
    "* Book Title\n",
    "* Default Paragraph Font\n",
    "* Emphasis\n",
    "* Heading 1 Char\n",
    "* Heading 2 Char\n",
    "* Heading 3 Char\n",
    "* Heading 4 Char\n",
    "* Heading 5 Char\n",
    "* Heading 6 Char\n",
    "* Heading 7 Char\n",
    "* Heading 8 Char\n",
    "* Heading 9 Char\n",
    "* Intense Emphasis\n",
    "* Intense Quote Char\n",
    "* Intense Reference\n",
    "* Macro Text Char\n",
    "* Quote Char\n",
    "* Strong\n",
    "* Subtitle Char\n",
    "* Subtle Emphasis\n",
    "* Subtle Reference\n",
    "* Title Char\n",
    "\n",
    "\n",
    "  </td>\n",
    "  \n",
    " </tr>\n",
    "\n",
    "</table>\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
